<template>
	<view class="location-select">
		<!-- 搜索框 -->
		<view class="search-box">
			<!--  -->
			<u-search
				v-model="searchText"
				:placeholder="searchPlaceholder"
				:show-action="false"
				@search="handleSearch"
				@change="handleSearch"
				@clear="clearSearch"
				:searchIcon="''"
			></u-search>
		</view>

		<!-- 当前地区 -->
		<view class="current-area">
			<view class="section-title">当前所在地区</view>
			<view class="location-item current-location" @click="selectCurrentLocation()">
				<image class="position-icon" src="/static/released/black-locat.png" mode="aspectFill"></image>
				<text>{{ currentLocation }}</text>
			</view>
		</view>

		<!-- 历史搜索 -->
		<view class="history-area" v-if="currentTabType != 'auth' && historyLocations.length > 0 && !searchText">
			<view class="section-header">
				<view class="section-title">历史搜索</view>
				<view class="clear-btn" @click="clearHistory">
					<image class="drive-del-icon" src="/static/personalCenter/auth-del.png" mode="aspectFill"></image>
					清空
				</view>
			</view>
			<view class="history-list">
				<view class="history-tag" v-for="(item, index) in historyLocations" :key="index" @click="selectLocation(item)">
					{{ item.cityArea.name }}
				</view>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view class="search-result" v-if="searchResult.length > 0">
			<view class="location-item" v-for="(item, index) in searchResult" :key="index" @click="selectLocation(item)">
				<image class="location-icon" src="/static/location.png" mode="aspectFill"></image>
				<text class="result-text">{{ item.name }}</text>
			</view>
		</view>

		<!-- 字母索引列表 -->
		<view class="index-list" v-if="showIndexList && !searchText">
			<!-- 右侧字母索引 -->
			<view class="index-bar" v-if="false">
				<view class="index-item" v-for="(item, index) in indexList" :key="index" @click="scrollToIndex(item)">
					{{ item }}
				</view>
			</view>

			<!-- 地区列表 -->
			<scroll-view scroll-y class="location-scroll" :scroll-into-view="scrollIntoId" @scroll="handleScroll">
				<view v-for="(group, index) in currentTabType == 'city' ? locationData : []" :key="index" :id="'index-' + group.letter" class="location-group">
					<view class="index-title">{{ group.letter }}</view>
					<view class="location-item" v-for="(location, lIndex) in group.locations" :key="lIndex" @click="selectLocation(location)">
						<text>{{ location.name }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 无结果提示 -->
		<view class="no-result" v-if="showNoResult">
			<u-empty mode="search" :icon="require('../../static/home/no-data.png')" text="暂无数据" textColor="#999"></u-empty>
		</view>
	</view>
</template>

<script>
import config from '@/config';
export default {
	data() {
		return {
			searchText: '',
			searchPlaceholder: '请输入市/县名称',
			currentLocation: '定位中...', // 默认当前地区
			historyLocations: [], //['成都市', '安岳县', '成都市', '安岳县'], // 历史记录
			searchResult: [],
			scrollIntoId: '',
			indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
			locationData: [],
			showIndexList: true,
			currentTabType: null,
			platform: ''
		};
	},
	computed: {
		showNoResult() {
			return this.searchText && this.searchResult.length === 0;
		}
	},
	onLoad(options) {
		// 获取当前设备信息
		const systemInfo = uni.getSystemInfoSync();
		this.platform = systemInfo.platform;

		this.currentTabType = options && options.activeTab;
		this.searchPlaceholder = options.activeTab === 'city' ? '请输入市/县名称' : '请输入城乡名称';
		// this.getCurrentLocation()
		this.getAreasData();
		this.loadHistory();

		// 配置微信签名
		this.initWeixinConfig();
	},
	onUnload() {
		// uni.$off('userLocation')
	},
	methods: {
		// 检测是否是微信环境
		isWeiXin() {
			return /micromessenger/i.test(navigator.userAgent);
		},
		// 初始化微信配置
		initWeixinConfig() {
			if (this.isWeiXin()) {
				this.getWeixinSignature();
			} else {
				uni.showToast({
					title: '配置微信config----当前环境不是微信环境',
					icon: 'none',
					duration: 5000
				});
			}
		},
		// 调用接口获取微信签名
		async getWeixinSignature() {
			try {
				const signUrl = this.platform === 'ios' ? uni.getStorageSync('firstIosUrl') : window.location.href.split('#')[0];
				const params = {
					url: signUrl
				};
				const res = await this.$http.post('/h5/wechat/getSignPackage', params);
				wx.config({
					debug: false,
					appId: res.data.appId,
					nonceStr: res.data.nonceStr,
					rawString: res.data.rawString,
					timestamp: res.data.timestamp,
					signature: res.data.signature,
					jsApiList: ['getLocation']
				});
				wx.ready(() => {
					this.localtionDo();
				});
			} catch (error) {}
		},
		localtionDo() {
			wx.getLocation({
				type: 'gcj02',
				isHighAccuracy: true, // 开启高精度定位
				highAccuracyExpireTime: 30000, // 高精度定位超时时间（毫秒）
				success: (res) => {
					const longitude = res.longitude;
					const latitude = res.latitude;
					this.requestLocation(longitude, latitude);
				},
				fail: (res) => {
					this.currentLocation = '定位失败';
				},
				complete: (res) => {
					if (res.errMsg !== 'getLocation:ok') {
						this.currentLocation = '定位失败';
					}
				}
			});
		},
		selectCurrentLocation() {
			if (this.currentLocation != '定位失败' || !this.currentLocation.includes('定位中')) {
				this.searchText = this.currentLocation;
				this.handleSearch();
			}

			this.getCurrentLocation();
		},
		// 获取当前位置
		getCurrentLocation() {
			uni.showLoading({
				title: '定位中...'
			});
			this.localtionDo();

			uni.hideLoading();
		},
		//发送请求坐标反解析
		requestLocation(longitude, latitude) {
			uni.request({
				url: 'https://restapi.amap.com/v3/geocode/regeo',
				method: 'GET',
				data: {
					key: config.mapKey,
					location: `${longitude},${latitude}`,
					output: 'JSON'
				},
				success: (res) => {
					if (res.data.infocode === '10000') {
						// 地址组成信息
						const addressComponent = res.data.regeocode.addressComponent;
						// 完整地址
						const address = res.data.regeocode.formatted_address;
						this.currentLocation = addressComponent.city;
					} else {
						uni.showToast({
							title: `定位失败：${res.errMsg}`,
							icon: 'none'
						});
						this.currentLocation = '定位失败';
					}
				}
			});
		},
		async getAreasData() {
			uni.showLoading({
				title: '数据加载中...',
				duration: 3000,
				mask: true
			});
			let params = {
				levels: this.currentTabType === 'city' ? [2] : [2, 3, 4] // 城际[2]   城乡[2,3]
			};
			try {
				if (this.currentTabType == 'city') {
					const data = await this.$http.post('/h5/common/areasByLevel', params);
					this.locationData = data.data;
				} else {
					const areaData = uni.getStorageSync('areaData');
					if (!areaData) {
						const data = await this.$http.post('/h5/common/areasByLevel', params);
						uni.setStorageSync('areaData', data.data);
						this.locationData = data.data;
					} else {
						this.locationData = areaData;
					}
				}

				uni.hideLoading();
			} catch (error) {}
		},

		// 获取历史记录
		async loadHistory() {
			if (!uni.getStorageSync('userInfo') || !uni.getStorageSync('userInfo').id) {
				return;
			}
			try {
				const data = await this.$http.get('/h5/line/getCityAreaSearchHistory');
				this.historyLocations = data.data.slice(0, 4);
			} catch (error) {}
		},
		// 保存历史记录
		async setHistory(id) {
			try {
				let params = {
					area_id: id,
					uid: (uni.getStorageSync('userInfo') && uni.getStorageSync('userInfo').id) || ''
				};
				const data = await this.$http.post('/h5/line/saveCityAreaSearchHistory', params);
				this.loadHistory();
			} catch (error) {}
		},

		// 保存历史记录
		saveHistory(location) {
			this.setHistory(location);
		},

		// 清空历史记录
		async clearHistory() {
			try {
				const data = await this.$http.get('/h5/line/clearCityAreaSearchHistory');
				uni.removeStorageSync('locationHistory');
				this.historyLocations = [];
				this.loadHistory();
			} catch (error) {}
		},

		// 搜索地点
		handleSearch() {
			if (!this.searchText.trim()) {
				this.searchResult = [];
				return;
			}
			const keyword = this.searchText.trim().toLowerCase();
			const result = [];
			Object.values(this.locationData).forEach((group) => {
				group.locations.forEach((city) => {
					if (city.name.toLowerCase().includes(keyword)) {
						result.push(city);
					}
				});
			});
			this.searchResult = result;
			this.showIndexList = false;
		},

		// 清除搜索
		clearSearch() {
			this.searchText = '';
			this.searchResult = [];
			this.showIndexList = true;
		},

		// 选择地点
		selectLocation(location) {
			console.log(location, '************');
			let resData = null;
			if (location.cityArea) {
				resData = {
					name: location.cityArea.name,
					id: location.cityArea.id
				};
			} else {
				resData = {
					name: location.name,
					id: location.id,
					level: location.level,
					type: location.type
				};
			}
			this.saveHistory(location.id);
			// 返回上级页面
			const pages = getCurrentPages();
			if (pages.length > 1) {
				const prevPage = pages[pages.length - 2];
				// 假设上级页面有setLocation方法
				if (prevPage.$vm.setLocation) {
					prevPage.$vm.setLocation(resData);
				}
				uni.navigateBack();
			}
		},

		// 滚动到指定字母
		scrollToIndex(letter) {
			this.scrollIntoId = 'index-' + letter;
		},

		// 处理滚动事件
		handleScroll(e) {
			// 可以根据滚动位置计算当前字母
			// 这里简化处理
		}
	}
};
</script>

<style lang="scss" scoped>
.location-select {
	background-color: #fff;
	display: flex;
	flex-direction: column;
}

.search-box {
	width: 700rpx;
	height: 88rpx;
	line-height: 88rpx;
	background: #f5f5f6;
	border-radius: 16rpx;
	margin: 12rpx 24rpx 32rpx 26rpx;

	.search-prefix {
		padding-right: 10rpx;
		color: #666666;
		font-size: 28rpx;
	}

	::v-deep .u-search__content__label {
		color: #999999;
		font-size: 28rpx;
	}
}

.section-title {
	padding: 0 0 0 26rpx;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 400;
	font-size: 28rpx;
	color: #999999;
	line-height: 42rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-right: 56rpx;
	margin-bottom: 24rpx;
}

.clear-btn {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 400;
	font-size: 28rpx;
	color: #999999;

	.drive-del-icon {
		width: 24rpx;
		height: 24rpx;
		margin-right: 8rpx;
	}
}

.current-area,
.history-area,
.search-result {
	margin-bottom: 30rpx;
}

.location-item {
	display: flex;
	align-items: center;
	padding: 20rpx;
	border-bottom: 2rpx solid #eeeeee;

	.position-icon {
		width: 32rpx;
		height: 32rpx;
	}

	text {
		margin-left: 10rpx;
	}

	.location-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.result-text {
		font-family: Source Han Sans CN, Source Han Sans CN;
		font-weight: 500;
		font-size: 32rpx;
		color: #0b1f20;
	}
}

.current-location {
	border: none;
	width: 160rpx;
	height: 64rpx;
	line-height: 64rpx;
	display: flex;
	justify-content: center;
	background: #f5f5f6;
	border-radius: 16rpx;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 400;
	font-size: 28rpx;
	padding: 0;
	margin-top: 24rpx;
	margin-left: 26rpx;
	color: #0b1f20;
}

.history-list {
	display: flex;
	flex-wrap: wrap;
	margin: 0 26rpx;
}

.history-tag {
	padding: 0 36rpx;
	height: 64rpx;
	text-align: center;
	background: #f5f5f6;
	border-radius: 16rpx;
	margin-right: 20rpx;
	margin-bottom: 15rpx;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 400;
	font-size: 28rpx;
	color: #0b1f20;
	line-height: 64rpx;
}

.index-list {
	flex: 1;
	display: flex;
	position: relative;
}

.index-bar {
	width: 50rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	position: fixed;
	right: 10rpx;
	top: 50%;
	transform: translateY(-50%);
	z-index: 10;
}

.index-item {
	width: 40rpx;
	height: 40rpx;
	line-height: 40rpx;
	text-align: center;
	font-size: 28rpx;
	color: #ff7937;
}

.location-scroll {
	flex: 1;
}

.location-group {
	margin-bottom: 20rpx;
}

.index-title {
	padding: 6rpx 26rpx;
	background-color: #f5f5f6;
	font-size: 28rpx;
	color: #999999;
}

.no-result {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;

	::v-deep .u-empty__text {
		font-size: 32rpx;
		color: #999999;
	}

	::v-deep .u-empty__image {
		width: 120rpx;
		height: 120rpx;
	}
}
</style>
